import Order, { IOrder } from "../models/Order";
import Product from "../models/Product";
import BlindBox from "../models/BlindBox";
import Member from "../models/Member";
import moment from "moment";
import _ from "lodash";
import mongoose from "mongoose";
import { faker } from "../../app";
import WxPay from 'wechatpay-node-v3';
import fs from 'fs'
import path from 'path'
import { log } from "console";


// 增加订单
export const addOrder = async (req: any, res: any) => {
    try {
        const { user, product, quantity, totalAmount, productType } = req.body;
        const newOrder = new Order({
            user,
            product,
            quantity,
            productType,
            totalAmount,
            createdAt: moment().format("YYYY-MM-DD HH:mm:ss"),
            updatedAt: moment().format("YYYY-MM-DD HH:mm:ss"),
        });
        await newOrder.save();
        res
            .status(201)
            .json({ status: "ok", message: "订单添加成功", data: newOrder });
    } catch (error: any) {
        res
            .status(500)
            .json({ status: "false", message: "订单添加失败", data: error.message });
    }
};

// 分页查询所有订单
export const getOrders = async (req: any, res: any) => {
    try {
        const page = parseInt(req.query.page as string) || 1;
        const limit = parseInt(req.query.limit as string) || 10;
        const skipIndex = (page - 1) * limit;
        const orders = await Order.find().sort({ createdAt: -1 }).skip(skipIndex).limit(limit);
        const total = await Order.countDocuments();
        res.json({
            status: "ok",
            message: "订单列表查询成功",
            total,
            page,
            limit,
            data: orders,
        });
    } catch (error: any) {
        res.status(500).json({
            status: "false",
            message: "订单列表查询失败",
            data: error.message,
        });
    }
};

// 根据订单 ID 查询订单
export const getOrderById = async (req: any, res: any) => {
    try {
        const orderId = req.params.id; // 从 URL 参数获取订单 ID
        const order = await Order.findById(orderId);

        if (!order) {
            return res.status(404).json({ status: "false", message: "订单未找到" });
        }

        res.json({ status: "ok", message: "订单查询成功", data: order });
    } catch (error: any) {
        res.status(500).json({
            status: "false",
            message: "查询订单时发生错误",
            data: error.message,
        });
    }
};

// 根据用户 ID 查询特定状态的订单
export const getOrdersByUserIdAndStatus = async (req: any, res: any) => {
    try {
        const userId = req.body.userId;
        const status = req.body.status;
        const orderId = req.body.orderId;
        //   const statuses = ['unPay', 'paid', 'consignment', 'finished'];

        let query: any = {
            "user._id": userId,
        };

        if (status !== "all") {
            query["status"] = { $in: status };
        }

        if (!_.isEmpty(orderId)) {
            if (orderId.length == 24) {
                query["_id"] = new mongoose.Types.ObjectId(orderId);
            } else {
                return res.json({ status: "ok", message: "订单查询成功", data: [] });
            }
        }

        const orders = await Order.find(query).sort({ updatedAt: -1 });

        if (orders.length === 0) {
            return res.json({ status: "ok", message: "订单查询成功", data: [] });
        }

        res.json({ status: "ok", message: "订单查询成功", data: orders });
    } catch (error: any) {
        console.error("查询订单时发生错误:", error.message);
        res.status(500).json({
            status: "false",
            message: "查询订单时发生错误",
            data: error.message,
        });
    }
};

// 根据用户 ID 统计不同状态的订单数量
export const countOrdersByStatusForUser = async (req: any, res: any) => {
    try {
        const userId = req.query.userId;

        const orderCounts = await Order.aggregate([
            {
                $match: {
                    "user._id": userId,
                },
            },
            {
                $group: {
                    _id: "$status",
                    count: { $sum: 1 },
                },
            },
        ]);

        console.log("orderCounts:", orderCounts);

        // 初始化计数
        const counts: any = {
            unPay: 0,
            paid: 0,
            consignment: 0,
            finished: 0,
            cancel: 0,
        };

        // 填充计数结果
        orderCounts.forEach((order) => {
            if (order._id in counts) {
                counts[order._id] = order.count;
            }
        });

        res.json({ status: "ok", message: "订单状态统计成功", data: counts });
    } catch (error: any) {
        res.status(500).json({
            status: "false",
            message: "统计订单状态时发生错误",
            data: error.message,
        });
    }
};

// 更新订单状态接口
export const updateOrderStatus = async (req: any, res: any) => {
    try {
        const { orderId, newStatus } = req.body;

        // 1. 查找订单并验证有效性
        const order = await Order.findById(new mongoose.Types.ObjectId(orderId));
        if (!order) {
            return res
                .status(500)
                .json({ status: "false", message: "订单不存在", data: null });
        }

        // 2. 更新订单状态
        order.status = newStatus;

        // 保存更新后的订单状态
        await order.save();

        res.json({ status: "ok", message: "订单状态更新成功！", data: null });
    } catch (error: any) {
        res.status(500).json({
            status: "false",
            message: "订单状态更新失败！",
            data: error.message,
        });
    }
};

export const generateOrders = async (req: any, res: any) => {
    const addNumber = 133;
    const user = await Member.aggregate([{ $sample: { size: 1 } }]);
    try {
        let count = 0;
        for (let i = 0; i < addNumber; i++) {
            const member = await Member.aggregate([{ $sample: { size: 1 } }]);
            const user = {
                _id: member[0]._id,
                username: member[0].username,
                fullName: member[0].fullName,
                phoneNumber: member[0].phoneNumber,
                level: member[0].level,
                isActive: member[0].isActive,
                createdAt: member[0].createdAt,
            };
            // console.log('user:', user)
            const blindBox = await BlindBox.aggregate([{ $sample: { size: 1 } }]);
            // console.log('blindBox:', blindBox)
            const quantity = faker.number.int({ min: 1, max: 10 });
            const product = {
                goodsId: blindBox[0]._id,
                name: blindBox[0].name,
                number: 1,
                image: blindBox[0].image,
                price: blindBox[0].price,
            };

            // 生成日期
            const createdAt = moment(
                faker.date.between({
                    from: "2023-6-1",
                    to: moment().format("YYYY-MM-DD"),
                })
            ).format("YYYY-MM-DD HH:mm:ss");
            const updatedAt = moment(
                faker.date.between({
                    from: createdAt,
                    to: moment().format("YYYY-MM-DD"),
                })
            ).format("YYYY-MM-DD HH:mm:ss");

            const newOrder = new Order({
                user,
                product,
                quantity,
                totalAmount: quantity * blindBox[0].price,
                status: faker.helpers.arrayElement(["pending", "cancel", "finished"]),
                createdAt,
                updatedAt,
            });
            const order = await newOrder.save();
            if (order) {
                count++;
            }
        }
        console.log("count::", count);
        if (count === addNumber) {
            res.status(201).send("批量生成订单数据成功");
        }
    } catch (error: any) {
        console.error("error:", error);
        res.status(500).json({ error: error.message });
    }
};


// 根据盲盒进行抽奖

export const handleLottery = async (orderId: string) => {
    const order = await Order.findById(orderId);
    // @ts-ignore
    const blindBox = await BlindBox.findById(order.product.goodsId);

    // 新增逻辑：根据盲盒的规则进行抽奖
    let lotteryResults: any[] = [];
    let hasWonAnyPrize = false; // 新增变量用于记录是否至少中了一个奖品
    // @ts-ignore
    if (blindBox.rule === "probability") {
        // @ts-ignore
        for (let i = 0; i < order.quantity; i++) {
            // @ts-ignore
            const productInfo = JSON.parse(blindBox.productInfo);
            const lotteryResult = drawLottery(productInfo);

            if (lotteryResult) {
                // 根据 _id 查询 Product 获取商品名称
                const productDetail = await Product.findById(lotteryResult._id);
                const productName = productDetail ? productDetail.title : "未知商品";

                lotteryResults.push({
                    attempt: i + 1,
                    result: productName,
                    image: productDetail?.images[0],
                });
                hasWonAnyPrize = true; // 更新中奖标志

                const productIndex = productInfo.findIndex(
                    (p: any) => p._id === lotteryResult._id
                );
                if (productIndex !== -1) {
                    productInfo[productIndex].amount -= 1;
                }
            } else {
                lotteryResults.push({ attempt: i + 1, result: "未中奖" });
            }
        }
        console.log("抽奖结果:", lotteryResults);
    }

    // ... [其余代码保持不变]

    /**
     * 根据商品配置的概率值进行随机抽奖
     * @param {Array} products 商品信息数组
     * @return {Object|null} 抽中的商品，未中奖时返回 null
     */
    function drawLottery(products: any[]) {
        // 过滤库存为 0 的商品
        const availableProducts = products.filter((p) => p.amount > 0);

        // 生成一个随机数
        const rand = Math.random();
        let cumulativeProbability = 0;

        // 根据随机数和商品的概率值选择商品
        for (const product of products) {
            cumulativeProbability += product.ruleValue / 100;
            if (rand <= cumulativeProbability) {
                return product;
            }
        }

        // 如果所有商品的概率之和小于随机数，则视为未中奖
        return null;
    }

    return {
        lotteryResults,
        hasWonAnyPrize
    }
}

export const afterPay = async (req: any, res: any) => {
    try {
        const { orderId, payType } = req.body;
        // console.log("afterPay orderId:", orderId);
        const order: any = await Order.findById(orderId);
        const member: any = await Member.findById(order.user);
        const blindBox: any = await BlindBox.findById(order.product.goodsId);
        order.status = "finished";
        const { lotteryResults } = await handleLottery(orderId)
        order.remark = JSON.stringify(lotteryResults);
        if (payType === 'alipay') {
            const product: any = await Product.findById(order.product.goodsId);
            member.balance = Number(member.balance) + Math.floor(order.totalAmount / 10)
            member.draws = member.draws + product.addDraws
            product.stock -= order.quantity
            await product.save();
        } else {
            member.balance -= order.totalAmount;
            blindBox.stock -= order.quantity;
        }

        // 保存更新后的数据
        await member.save();
        await blindBox.save();
        await order.save();

        res.json({
            status: "ok",
            message: "支付成功！",
            data: order,
        });
    } catch (error: any) {
        res.status(500).json({
            status: "false",
            message: "支付失败",
            data: error.message,
        });
    }
}


export const weixinNotify = async (req: any, res: any) => {
    console.log('微信支付回调！')

    const payment = new WxPay({
        appid: 'wxdd3e756f42838499',
        mchid: '1668468944',
        publicKey: fs.readFileSync(path.resolve(__dirname, './order/wx_cert.pem')), // 公钥
        privateKey: fs.readFileSync(path.resolve(__dirname, './order/wx_key.pem')), // 秘钥
        // apiv3Key: '18682304124cgc440803199212030718'
    });


    try {
        const decrypted: any = await payment.decipher_gcm(
            req.body.resource.ciphertext,
            req.body.resource.associated_data,
            req.body.resource.nonce,
            '18682304124cgc440803199212030718'
        )
        console.log('查询微信订单结果：', decrypted)
        console.log('trade_state', decrypted.trade_state)

        if (decrypted.trade_state === 'SUCCESS') {
            // 处理订单状态更新
            const orderId = decrypted.out_trade_no;
            const order: any = await Order.findById(orderId);
            // console.log('order', order)
            const member: any = await Member.findById(order.user);
            // console.log('member', member)
            const product: any = await Product.findById(order.product.goodsId);
            // console.log('product', product)

            product.stock -= order.quantity
            order.status = 'finished'
            order.payInfo = decrypted
            member.balance = Number(member.balance) + Math.floor(order.totalAmount / 10)
            member.draws += product.addDraws

            // 保存更新后的数据
            await member.save();
            await product.save();
            console.log('order', order)
            await order.save();

            if (!order) {
                return res.status(404).json({
                    status: 'error',
                    message: '订单不存在',
                });
            }

            res.status(200).send('success')
        } else {
            console.log('回调失败')
            res.status(400).json({
                status: 'error',
                message: '回调失败',
            });
        }
    } catch (error: any) {
        console.log('服务器错误')
        res.status(500).json({
            status: 'error',
            message: '服务器错误',
            error: error.message,
        });
    }
}